class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        return_out = []

        def dfs(node):
            if not node:
                return False, False
            else:
                if node == p:
                    right_flag = dfs(node.left)[1] or dfs(node.right)[1]
                    left_flag = True
                else:
                    if node == q:
                        left_flag = dfs(node.left)[0] or dfs(node.right)[0]
                        right_flag = True
                    else:
                        left_1, right_1 = dfs(node.left)
                        left_2, right_2 = dfs(node.right)
                        left_flag = left_1 or left_2
                        right_flag = left_2 or right_2
                if left_flag and right_flag and not return_out:
                    return_out.append(node)
                return left_flag, right_flag

        dfs(root)
        return return_out[0]
